﻿using System;
using System.Collections.Generic;
using System.Text;
using Opalis.QuickIntegrationKit;
using System.Management;
using System.Management.Instrumentation;
using OpalisSCCMInterop;
using Microsoft.ConfigurationManagement;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;

namespace OpalisSCCMExtension
{
    [OpalisObject("Associate SCCM Computer Record")]
    public class AssociateComputerRecord : IOpalisObject
    {
        private ConnectionCredentials settings;
        private String userName = String.Empty;
        private String password = String.Empty;
        private String SCCMServer = String.Empty;

        private int ObjCount = 0;

        [OpalisConfiguration]
        public ConnectionCredentials Settings
        {
            get { return settings; }
            set { settings = value; }
        }
        public void Design(IOpalisDesigner designer)
        {
            WqlConnectionManager connection = CMInterop.connectSCCMServer(settings.SCCMSERVER, settings.UserName, settings.Password);

            designer.AddInput("Reference Computer Resource ID");
            designer.AddInput("Destination Computer Resource ID");

            designer.AddCorellatedData(typeof(system));
            designer.AddOutput("Number of Systems");
        }
        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            SCCMServer = settings.SCCMSERVER;
            userName = settings.UserName;
            password = settings.Password;

            int referenceID = (int)request.Inputs["Reference Computer Resource ID"].AsUInt32();
            int destinationID = (int)request.Inputs["Destination Computer Resource ID"].AsUInt32();


            //Setup WQL Connection and WMI Management Scope
            WqlConnectionManager connection = CMInterop.connectSCCMServer(SCCMServer, userName, password);

            CMInterop.associateComputer(connection, referenceID, destinationID);

            IResultObject col = null;
            col = CMInterop.getSCCMComputer(connection, Convert.ToString(destinationID), "", "");

            if (col != null)
            {
                response.WithFiltering().PublishRange(getObjects(col));

            }
            response.Publish("Number of Systems", ObjCount);
        }
        private IEnumerable<system> getObjects(IResultObject objList)
        {
            foreach (IResultObject obj in objList)
            {
                ObjCount++;
                yield return new system(obj);
            }
        }
    }
}
